<script setup>
import { onMounted, ref, watch } from 'vue'


const props = defineProps(['categoryIds','currentIndex'])
const emit = defineEmits(['currentIndexChange'])
console.log(props)

watch(props.categoryIds, (newVal, oldVal) => {
    console.log("segement categoryIds change");
})

function segmentClick(index) {
    
    console.log(index);
    emit('currentIndexChange', index)
    // 如果当前选择的按钮超过了可视范围，就滚动到可视范围
    const scrollview = document.getElementsByClassName('segment-content')[0];
    const item = document.getElementsByClassName('segment-item')[index];
    const itemLeft = item.offsetLeft;
    const itemWidth = item.offsetWidth;
    const scrollviewLeft = scrollview.scrollLeft;
    const scrollviewWidth = scrollview.offsetWidth;
    const itemRight = itemLeft + itemWidth;
    const scrollviewRight = scrollviewLeft + scrollviewWidth;
    if(itemRight + 20 > scrollviewRight){
        console.log("右侧溢出");
        scrollview.scrollLeft = Math.max(0, itemRight + 20 - scrollviewRight);
    }else if (itemLeft - 20 < scrollviewLeft) {
        console.log("左侧溢出");
        scrollview.scrollLeft = Math.max(0, itemLeft - 20);
    }else{
        console.log("不溢出");
    }
}

onMounted(() => {

});

</script>

<template>

    <div class="segment-content scrollview">
        <span v-for="(item, index) in categoryIds" 
        @click="segmentClick(index)"
        class="segment-item"
        :class="(index === currentIndex) ? 'segment-item-selected' : ''" :key="item.id">
            {{ item.name }}
        </span>
    </div>
</template>

<style scoped>
.segment-content {
    box-sizing: border-box;
    width: 100%;
    overflow-x: scroll;
    display: flex;
    padding-left: 20px;
    padding-right: 20px;
    scroll-behavior: smooth;
    /* justify-content: space-around;
    align-items: center; */
}

.segment-item {
    margin: 10px;
    text-align: center;
    cursor: none;
    white-space: nowrap;
    font-size: 14px;
    line-height: 44px;
    color: #5a5a5a;
}

.segment-item-selected {
    color: #363636;
    font-weight: 500;
    border-bottom: 2px solid #363636;
}
</style>